package service

import (
	//"fmt"
	"os"
	"net/http"
	"text/template"
	"log"
	"github.com/urfave/negroni"
	"github.com/gorilla/mux"
	"github.com/unrolled/render"
)

func NewServer() *negroni.Negroni{
	mx := mux.NewRouter()
	n := negroni.Classic()

	formatter := render.New(render.Options{
		Directory:  "templates",
		Extensions: []string{".html"},
		IndentJSON: true,
	})

	initRoutes(mx, formatter)
	n.UseHandler(mx)
	return n
}

func initRoutes(mx *mux.Router, formatter *render.Render) {
	webRoot := os.Getenv("WEBROOT")
	if len(webRoot) == 0 {
		if root, err := os.Getwd(); err != nil {
			panic("Could not retrive working directory")
		} else {
			webRoot = root
		}
	}
	mx.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir(webRoot+"/assets/staticFiles"))))
	mx.PathPrefix("/json/").Handler(http.StripPrefix("/json/", http.FileServer(http.Dir(webRoot+"/assets/jsonFiles"))))
	mx.HandleFunc("/api/test",jsonHandler(formatter)).Methods("GET")
	mx.HandleFunc("/login", loginHandler(formatter))
	mx.PathPrefix("/").Handler(http.FileServer(http.Dir(webRoot+"/assets/")))
}

func jsonHandler(formatter *render.Render) http.HandlerFunc{
	return func(w http.ResponseWriter, req *http.Request){
		formatter.JSON(w, http.StatusOK, struct {
			ID      string `json:"id"`
			Content string `json:"content"`
		}{ID: "8675309", Content: "Hello from Go!"})
	}
}

func loginHandler(formatter *render.Render) http.HandlerFunc{
	ret := func(w http.ResponseWriter, r *http.Request){
		if r.Method == "GET" {
			t, _ := template.ParseFiles("assets/loginFiles/login.gtpl")
			log.Println(t.Execute(w, nil))
		} else {
			r.ParseForm()
			formatter.HTML(w, http.StatusOK, "index", struct {
				Un string `json:"username"`
				Pw string `json:"password"`
			}{Un: r.Form["username"][0], Pw: r.Form["password"][0]})
		}
	}
    return ret
}